package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 这个类的作用: 定时任务类, 项目启动就执行,每隔24小时去授权中心申请一次token
 */
@Slf4j
@Component
public class AppTokenHolder {

    //token刷新间隔时间
    private final static long LOAD_TOKEN_TIME = 86400000L;
    //获取token休眠时间
    private final static long LOAD_TOKEN_SLEEP_TIME = 10000L;

    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProperties;

    @Getter
    private String token;

    @Scheduled(fixedDelay = LOAD_TOKEN_TIME)
    public void loadTokenTask() throws InterruptedException {
        while (true){
            try {
                this.token = authClient.authorize(jwtProperties.getApp().getId(), jwtProperties.getApp().getSecret());
                log.info("【网关微服务】申请token成功");
                break;
            } catch (Exception e){
                log.error("【网关微服务】申请token失败: {}",e.getMessage());
            }
            Thread.sleep(LOAD_TOKEN_SLEEP_TIME);
        }
    }

}
